package com.qb.devstore;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xuexiang.xui.XUI;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.AppUtil;
import utils.DevInfoUtil;
import utils.MyUtil;
import utils.NotificationUtil;

public class ViewActivity extends AppCompatActivity {

    private Context ctx;
    public static ViewActivity vActivity;
    private ViewPager mViewPager;
    private List<View> mViews;  //存放视图的数组
    private View view1,view2,view3;
    private PagerAdapter mPagerAdapter;//适配器
    private TextView tvView1,tvView2,tvView3,tvTitle1,tvTitle2,tvTitle3;
    private RecyclerView rvView1,rvView2,rvView3;
    private JSONArray appListData;
    SharedPreferences SP;
    MiniLoadingDialog mMiniLoadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        XUI.initTheme(this);
        XToast.Config.get().setGravity(Gravity.CENTER);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.setDialogSize(150,150);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        StatusBarUtils.initStatusBarStyle(this, false, 0x00000000);
        ctx = ViewActivity.this;
        vActivity = this;
        SP = getSharedPreferences("dev_mgt_setting", this.MODE_PRIVATE);
        SharedPreferences.Editor edit = SP.edit();
        edit.putString("baseUrl","https:///www.androidgmt.com/manager");
        edit.apply();

        viewPagerInit();
        login();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NotificationUtil nu = new NotificationUtil(ctx);
        nu.clearNotification();
    }

    // 登录获取信息
    public void login() {
        String post_sn = DevInfoUtil.getSN()+"@|@"+"AppStore";
        httpAction("login","/AndroidGmtService/Token/TakeToken?board_sn_process="+post_sn,"post","");
    }

    public void loginResult(JSONArray data) {
        try {
            SharedPreferences.Editor edit = SP.edit();
            JSONObject d0 = new JSONObject(data.get(0).toString());
            String token = d0.getString("token");
            edit.putString("token",token);
            edit.apply();
            searchIsLoad = false;
            tabItemInit();
        } catch (JSONException e) {
            showMsgBar("鉴权失败",e.getMessage());
            e.printStackTrace();
        }
    }
    // viewpager
    private void viewPagerInit() {
        mViewPager=findViewById(R.id.viewpager);// 实例化viewpager控件

        LayoutInflater inflater = getLayoutInflater();//获取布局对象管理
        view1 = inflater.inflate(R.layout.layout_view1,null);//实例化view
        view2 = inflater.inflate(R.layout.layout_view3,null);
        view3 = inflater.inflate(R.layout.layout_view3,null);

        mViews=new ArrayList<View>();//将要显示的布局存放到list数组
        mViews.add(view1);
        mViews.add(view2);
        //mViews.add(view3);

        //实例化一个PagerAdapter的适配器
        mPagerAdapter=new PagerAdapter() {
            @Override   //返回要滑动的VIew的个数
            public int getCount() {
                return mViews.size();
            }

            @Override  //来判断pager的一个view是否和instantiateItem方法返回的object有关联
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view==object;
            }

            @Override  //从当前container中删除指定位置（position）的View;
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(mViews.get(position));
            }

            @NonNull
            @Override  //第一：将当前视图添加到container中，第二：返回当前View
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(mViews.get(position));
                return mViews.get(position);
            }
        };
        mViewPager.setAdapter(mPagerAdapter);//设置适配器
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //MyUtil.showLog("onPageScrolled",positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                tabItemSeleted(position, true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //MyUtil.showLog("onPageScrollStateChanged",state);
            }
        });
    }

    // 导航按钮
    Drawable d1,d1_a,d2,d2_a,d3,d3_a;
    private void tabItemInit() {
        tvView1 = findViewById(R.id.tv_view1);
        tvView2 = findViewById(R.id.tv_view2);
        tvView3 = findViewById(R.id.tv_view3);
        tvView3.setVisibility(View.GONE);
        d1 = ctx.getResources().getDrawable(R.drawable.ic_baseline_star_64);
        d1.setBounds( 0, 0, d1.getMinimumWidth(),d1.getMinimumHeight());
        d1_a = ctx.getResources().getDrawable(R.drawable.ic_baseline_star_64_active);
        d1_a.setBounds( 0, 0, d1.getMinimumWidth(),d1.getMinimumHeight());
        d2 = ctx.getResources().getDrawable(R.drawable.ic_baseline_apps_64);
        d2.setBounds( 0, 0, d1.getMinimumWidth(),d1.getMinimumHeight());
        d2_a = ctx.getResources().getDrawable(R.drawable.ic_baseline_apps_64_active);
        d2_a.setBounds( 0, 0, d1.getMinimumWidth(),d1.getMinimumHeight());
        d3 = ctx.getResources().getDrawable(R.drawable.ic_baseline_cached_64);
        d3.setBounds( 0, 0, d1.getMinimumWidth(),d1.getMinimumHeight());
        d3_a = ctx.getResources().getDrawable(R.drawable.ic_baseline_cached_64_active);
        d3_a.setBounds( 0, 0, d1.getMinimumWidth(),d1.getMinimumHeight());
        tabItemSeleted(0, true);

        tvView1.setOnClickListener(view -> {
            mViewPager.setCurrentItem(0);
        });
        tvView2.setOnClickListener(view -> {
            mViewPager.setCurrentItem(1);
        });
        tvView3.setOnClickListener(view -> {
            mViewPager.setCurrentItem(1);
        });
    }
    // tab选中
    private void tabItemSeleted(int item, Boolean loadData) {
        tvView1.setCompoundDrawables(null,d1,null,null);
        tvView2.setCompoundDrawables(null,d2,null,null);
        tvView3.setCompoundDrawables(null,d3,null,null);
        tvView1.setTextColor(getResources().getColor(R.color.tab_default));
        tvView2.setTextColor(getResources().getColor(R.color.tab_default));
        tvView3.setTextColor(getResources().getColor(R.color.tab_default));
        if (item == 0) {
            tvView1.setCompoundDrawables(null,d1_a,null,null);
            tvView1.setTextColor(getResources().getColor(R.color.primary_normal));
        }
        if (item == 1) {
            tvView2.setCompoundDrawables(null,d2_a,null,null);
            tvView2.setTextColor(getResources().getColor(R.color.primary_normal));
        }
        if (item == 2) {
            tvView3.setCompoundDrawables(null,d3_a,null,null);
            tvView3.setTextColor(getResources().getColor(R.color.primary_normal));
        }
        if (loadData) {
            mViewPager.setCurrentItem(item);
            rvViewInit(item);
        }
    }

    // 查询app列表
    int var_item = 0;
    Boolean searchIsLoad = false;
    Boolean listIsLoad = false;
    Boolean installIsLoad = false;
    int indexPage = 1;
    int pageSize = 100;
    Boolean moreAppData = true;
    private void rvViewInit(int item) {
        MyUtil.showLog("rvViewInit",item);
        var_item = item;
        if (item == 0) {
            if (!searchIsLoad) {
                getApps(indexPage,pageSize,"");
            }
//        } else if (item == 1) {
//            if (!listIsLoad) {
//                getApps(indexPage,pageSize,"");
//            }
        } else if (item == 1) {
            if (!installIsLoad) {
                mMiniLoadingDialog.show();
                new Handler().postDelayed(()-> {
                    rvViewResult(AppUtil.getAppList(ctx));
                },300);
            }
        }
    }
    private void getMoreApps() {
        MyUtil.showLog("getMoreApps indexPage:"+indexPage+",more:"+moreAppData,"");
        if (moreAppData) {
            getApps(indexPage,pageSize,"");
        }
    }

    // RecyclerView init
    private void rvViewResult(JSONArray data) {
        MyUtil.showLog("rvViewResult"+searchIsLoad,data);
        if (var_item == 1) moreAppData = data.length() >= pageSize;
        tvTitle1 = findViewById(R.id.tv_title1);
        tvTitle2 = findViewById(R.id.tv_title2);
        tvTitle3 = findViewById(R.id.tv_title3);
        rvView1 = findViewById(R.id.rv_view1);
//        rvView1.setVisibility(View.GONE);
        rvView2 = findViewById(R.id.rv_view2);
        rvView3 = findViewById(R.id.rv_view3);
        GridLayoutManager appGLM = new GridLayoutManager(this,4);
        AppAdapter appAdapter;
        if (var_item == 0) {
            appAdapter = new AppAdapter(this, data);
            rvView1.setLayoutManager(appGLM);
            if(rvView1.getRecycledViewPool()!=null){
                rvView1.getRecycledViewPool().setMaxRecycledViews(appAdapter.getItemViewType(0), 500);
            }
            rvView1.setAdapter(appAdapter);
            if (MyUtil.isNull(data)) {
                tvTitle1.setVisibility(View.VISIBLE);
                if (keyWords.equals("")) {
                    tvTitle1.setText("应用商店列表为空，请到终端管理平台上架应用");
                } else {
                    tvTitle1.setText("没有名称关键字匹配的应用");
                }
            } else {
                tvTitle1.setVisibility(View.GONE);
//                rvView1.setVisibility(View.VISIBLE);
            }
            /*ImageView ivBanner = findViewById(R.id.iv_banner);
            if (searchIsLoad) {
                tvTitle1.setText("搜索到"+data.length()+"个结果");
                ivBanner.setVisibility(View.GONE);
                rvView1.setVisibility(View.VISIBLE);
                //rvView1.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
            } else {
                tvTitle1.setText("");
                ivBanner.setVisibility(View.VISIBLE);
                rvView1.setVisibility(View.GONE);
                //rvView1.getLayoutParams().height = 260;
            }*/

            Button btnSearch = findViewById(R.id.btn_search);
            btnSearch.setOnClickListener(view -> {
                EditText etSearch = findViewById(R.id.et_search);
                getApps(1,100, String.valueOf(etSearch.getText()).trim());
            });
            searchIsLoad = true;
        }
//        if (var_item == 1) {
//            if (!listIsLoad) {
//                rvView2.addOnScrollListener(new RecyclerView.OnScrollListener() {
//                    @Override
//                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//                        super.onScrolled(recyclerView, dx, dy);
//                        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
//                        int itemCount = layoutManager.getItemCount();
//                        if (lastVisibleItemPosition == itemCount - 1) {
//                            // RecyclerView已经滚动到了底部
//                            getMoreApps();
//                        }
//                    }
//                });
//            }
//            MyUtil.showLog("app indexPage:"+indexPage,"");
//            if (indexPage == 1) appListData = data;
//            else appListData = MyUtil.joinJSONArray(appListData,data);
//            MyUtil.showLog("appListData",appListData);
//            try {
//                appListData.length();
//            } catch (Exception e) {
//                appListData = new JSONArray();
//            }
//            appAdapter = new AppAdapter(this, appListData);
//            rvView2.setLayoutManager(appGLM);
//            rvView2.setAdapter(appAdapter);
//            tvTitle2.setText(appListData.length()==0?"请登录安卓管理平台设置应用":"应用列表");
//            listIsLoad = true;
//            indexPage++;
//        }
        if (var_item == 1) {
            appAdapter = new AppAdapter(this, data);
            rvView3.setLayoutManager(appGLM);
            rvView3.setAdapter(appAdapter);
            tvTitle3.setText("已安装的应用");
            installIsLoad = true;
        }

        new Handler().postDelayed(()-> {
            mMiniLoadingDialog.dismiss();
        },300);
    }

    // 查询app
    private String keyWords = "";
    private void getApps(int indexPage, int pageSize, String key) {
        if (key.equals("")) {
            installIsLoad = false;
        } else {
            if (keyWords.equals(key)) return;
        }
        keyWords = key;
        if (false && key.equals("") && var_item == 0) {
            tvTitle1.setText("");
            ImageView ivBanner = findViewById(R.id.iv_banner);
            ivBanner.setVisibility(View.VISIBLE);
        } else {
            JSONObject p = new JSONObject();
            try {
                String url = "/AndroidGmtService/AppStore/QryStoreApps";
                p.put("id",DevInfoUtil.getSN()+"@|@"+"AppStore");
                p.put("token",SP.getString("token",""));
                p.put("name",key);
                p.put("remark","");
                httpAction("apps",url,"post",p.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    // 显示cookiebar
    public void showMsgBar(String title,String msg) {
        MyUtil.showCookieBar(ctx,title,msg,"login");
        mMiniLoadingDialog.dismiss();
    }

    /*
     * http
     * */
    public void httpAction(String flag,String url,String method,String postJson) {
        String BaseUrl = SP.getString("baseUrl","");
        if (BaseUrl.indexOf(".") < 10) {
            XToastUtils.error("无效的服务器"+BaseUrl, Toast.LENGTH_LONG);
            return;
        }
        url = BaseUrl+url;
        String token = SP.getString("token","");
        MyUtil.showLog("httpAction",flag);
        MyUtil.showLog("",url);
        MyUtil.showLog("",method);
        MyUtil.showLog("",postJson);
        MyUtil.showLog("token",token);
        if (flag.equals("login")) {
            mMiniLoadingDialog.updateMessage("登录中");
            mMiniLoadingDialog.setDialogSize(150,150);
        } else {
            mMiniLoadingDialog.updateMessage("加载中");
            mMiniLoadingDialog.setDialogSize(150,150);
        }
        if (indexPage == 1) mMiniLoadingDialog.show();
        OkHttpClient ohc = new OkHttpClient();
        Request request = null;
        if (method.equals("get")) {
            request = new Request.Builder().url(url)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        if (method.equals("post")) {
            RequestBody requestBody;
            if (flag.equals("login")) {
                // formBody
                HashMap<String,String> paramsMap = new HashMap<>();
                paramsMap.put("board_sn_process",postJson);
                FormBody.Builder builder = new FormBody.Builder();
                for (String key : paramsMap.keySet()) {
                    builder.add(key, paramsMap.get(key));
                }
                requestBody = builder.build();
            } else {
                // json
                requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postJson);
            }
            request = new Request.Builder().url(url).post(requestBody)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        ohc.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                MyUtil.showLog("httpAction onFailure",e.getMessage());
                runOnUiThread(() -> {
                    showMsgBar("网络连接失败",e.getMessage());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                successResult(response, flag);
            }
        });
    }
    public void successResult(Response res, String flag) {
        runOnUiThread(() -> {
           //mMiniLoadingDialog.dismiss();
        });
        if (res.code() == 200) {
            try {
                String r = "{}";
                try {
                    r = res.body().string();
                    MyUtil.showLog("httpAction success",r);
                } catch (Exception e) {
                    XToastUtils.error("HTTP返回数据获取失败 "+e.getMessage(), Toast.LENGTH_LONG);
                    e.printStackTrace();
                }
                JSONObject rObj = new JSONObject(r);
                String rCode = rObj.get("returnCode").toString();
                String rMsg = rObj.get("message").toString();
                if (rCode.equals("10000")) {
                    String dStr = rObj.get("data").toString();
                    JSONArray data = new JSONArray(MyUtil.isNull(dStr)?"[]":dStr);
                    runOnUiThread(() -> {
                        if (flag.equals("login")) {
                            mMiniLoadingDialog.dismiss();
                            loginResult(data);
                        }
                        if (flag.equals("apps")) {
                            try {
                                //MyUtil.showLog("data",data);
                                if (MyUtil.isNull(data) || data.toString().equals("[null]")) {
                                    //XToastUtils.warning("应用商店列表为空，请到终端管理平台上架应用", Toast.LENGTH_LONG);
                                    rvViewResult(new JSONArray("[]"));
                                } else {
                                    JSONArray apps = data.getJSONArray(0);
                                    //MyUtil.showLog("apps",apps);
                                    /*
                                    for (int i=0;i<apps.length();i++) {
                                        // 图片url转base64
                                        int finalI = i;
                                        ImgUtil iu = new ImgUtil();
                                        String apkIcon = apps.getJSONObject(i).getString("appicon");
//                                        apkIcon = "https://pic.616pic.com/ys_img/00/13/07/gqliRoueDE.jpg";
//                                        String apkUrlTest = "http://192.168.6.86:8086/xiazaiba/预装app/酷安应用市场.apk";
//                                        apps.getJSONObject(finalI).put("url",apkUrlTest);

                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Bitmap bitmap = null;
                                                URL imageurl = null;
                                                try {
                                                    imageurl = new URL(apkIcon);
                                                } catch (MalformedURLException e) {
                                                    e.printStackTrace();
                                                }
                                                try {
                                                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                                                    conn.setDoInput(true);
                                                    conn.connect();
                                                    InputStream is = conn.getInputStream();
                                                    bitmap = BitmapFactory.decodeStream(is);

                                                    Drawable drawable = iu.bitmap2Drawable(bitmap);
                                                    drawable.setBounds(0, 0, 96,96);
                                                    Bitmap bmNew = iu.drawable2Bitmap(drawable);
                                                    apps.getJSONObject(finalI).put("icon",iu.getImgStr(bmNew));

                                                    is.close();
                                                } catch (IOException | JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }).start();
                                    }*/
                                    rvViewResult(apps);
                                }
                            } catch (JSONException e) {
                                XToastUtils.error(e.getMessage(), Toast.LENGTH_LONG);
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    runOnUiThread(() -> {
                        //XToastUtils.error(rMsg, Toast.LENGTH_LONG);
                        showMsgBar("查询失败",rMsg);
                    });
                }
            } catch (JSONException e) {
                runOnUiThread(() -> {
                    showMsgBar("查询失败",e.getMessage());
                });
                e.printStackTrace();
            }
        } else {
            runOnUiThread(() -> {
                showMsgBar("网络连接失败","错误码："+res.code());
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyUtil.showLog("requestCode view",requestCode);
    }

}